<?php

namespace plugin\ycMassage\app\model;

use think\facade\Cache;

class MassageUserTechnicianScheduling extends Model
{
    public static function getNextAppointmentTime(MassageUserTechnicianScheduling $Scheduling, $duration)
    {
        $Matrix = MassageAppointmentService::createMatrix($Scheduling->id, $Scheduling->start_time, $Scheduling->end_time);
        # Matrix[] start_time：开始时间 end_time：结束时间 state：0：未预约 1：已预约
        # 判断是否有可预约的时间，至少时长为70分钟
        $appointment_time = null;
        $durationSum = 0;
        foreach ($Matrix as $key => $value) {
            if ($value['state'] == 0 && $value['start_time'] >= time()) {
                if (!$appointment_time) {
                    $appointment_time = $value['start_time'];
                }
                $durationSum += $value['duration'];
                if ($durationSum >= $duration) {
                    break;
                }
            } else {
                if ($durationSum < $duration) {
                    $appointment_time = null;
                    $durationSum = 0;
                }
            }
        }
        return $appointment_time;
    }
    public static function createAdjustSchedulingMonthMatrix()
    {
        $cacheKey = 'scheduling.' . date('Y-m');
        if ($data = Cache::get($cacheKey)) {
            return $data;
        }
        # 根据当前月和下一个月创建一个二维数组
        $month = (int)date('m');
        $monthStart = (int)date('d', strtotime('first day of this month'));
        $monthEnd = (int)date('d', strtotime('last day of this month'));

        $tomonth = (int)date('m', strtotime('+1 month'));
        $tomonthStart = (int)date('d', strtotime('first day of next month'));
        $tomonthEnd = (int)date('d', strtotime('last day of next month'));
        $data = [
            'month' => [],
            'tomonth' => []
        ];
        for ($i = $monthStart; $i <= $monthEnd; $i++) {
            $day_time = date('Y/m/' . $i);
            $temp = [
                'day' => $i,
                'month' => $month,
                'day_time' => $day_time,
                'start_time' => $day_time . ' 00:00:00',
                'end_time' => $day_time . ' 23:59:59'
            ];
            $temp['week'] = (int)date('w', strtotime($temp['start_time']));
            $data['month'][] = $temp;
        }
        for ($i = $tomonthStart; $i <= $tomonthEnd; $i++) {
            $day_time = date('Y/m/' . $i, strtotime('+1 month'));
            $temp = [
                'day' => $i,
                'month' => $tomonth,
                'day_time' => $day_time,
                'start_time' => $day_time . ' 00:00:00',
                'end_time' => $day_time . ' 23:59:59'
            ];
            $temp['week'] = (int)date('w', strtotime($temp['start_time']));
            $data['tomonth'][] = $temp;
        }
        $ttl = strtotime('last day of this month 23:59:59') - time();
        Cache::set($cacheKey, $data, $ttl);
        return Cache::get($cacheKey);
    }
}
